package com.xxkj.drugtraceability.ui.prescriptiondrugcollection

import android.app.Application
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.xxhis.drugtraceability.base.BaseViewModel
import com.xxkj.drugtraceability.bean.DrugDictDataList
import com.xxkj.drugtraceability.bean.FinishRequest
import com.xxkj.drugtraceability.bean.PrescriptionInfoBean
import com.xxkj.drugtraceability.bean.PrescriptionRequest
import com.xxkj.drugtraceability.bean.TraceRequest
import com.xxkj.drugtraceability.net.Result
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * author: zhoujingjin
 * created on: 2024/9/10 16:15
 * description:
 */
class PrescriptionDrugCollectionViewModel(application: Application,private val repository: PrescriptionDrugCollectionRepository):BaseViewModel(application) {
    var prescriptioninfo = MutableLiveData<List<PrescriptionInfoBean>?>()
    var baseUiModel = MutableLiveData<BaseUiModel<Boolean>>()
    //是否可以扫溯源码，如果处方码已经保存过追溯码，无论保存的多少，都不再让保存了。
    var canAdd = true
    var selectIndex = MutableLiveData(-1)
    var lastIndex = -1
    var barcode = ""
    var Prescriptionbarcode = ""
    var usedCount: String = "0"
    var trugTracCodgIsGatherData:DrugDictDataList? = null
    fun getPrescriptionInfo(barcode:String){
        viewModelScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                baseUiModel.postValue(BaseUiModel(showLoading = true))
                val result = repository.queryPrescriptionInfoList(Gson().toJson(PrescriptionRequest(barcode,"1")))
                if (result is Result.Success){
                    Prescriptionbarcode = barcode
                    if(result.data.data.isNotEmpty()){
                        prescriptioninfo.postValue(result.data.data)
                        result.data.data[0].drugInfoList.forEach  {
                            canAdd = it.drugTracInfoList.isNullOrEmpty()
                            if (!canAdd){
                                return@forEach
                            }
                        }
                    }else{
                        prescriptioninfo.postValue(null)
                    }
                    baseUiModel.postValue(BaseUiModel(showLoading = false))
                }else if (result is Result.Error){
                    baseUiModel.postValue(BaseUiModel(showLoading = false,showError = result.errorData?:result.exception.message))
                }
            }
        }
    }
    fun trugTracCodgIsGather(barcode:String){
        viewModelScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                baseUiModel.postValue(BaseUiModel(showLoading = true))
                this@PrescriptionDrugCollectionViewModel.barcode = barcode
                val result = repository.trugTracCodgIsGather(Gson().toJson(TraceRequest(barcode,"1")))
                if (result is Result.Success){
                    if (result.data.data.isGather){

                        if (!result.data.data.isCheckUsedCount.isNullOrEmpty()&&"1"==result.data.data.isCheckUsedCount) {
                            if (!result.data.data.usedCount.isNullOrEmpty()) {
                                usedCount = result.data.data.usedCount
                            }
                        }
                        if (result.data.data.drugDictInfo==null){
                            baseUiModel.postValue(BaseUiModel(showLoading = false,showError = "未找到与溯源码匹配的药品,请手动选中到待扫描的药品"))
                        }
                        else{
                            trugTracCodgIsGatherData = result.data.data
                            var indexTemp = -1
                            run layer@{
                                prescriptioninfo.value?.get(0)?.drugInfoList?.forEachIndexed { index, drugInfoBean ->
                                    result.data.data.drugDictInfo.forEach { resultDrugDictInfo ->
                                        if (resultDrugDictInfo.drugCode == drugInfoBean.drugCode && !drugInfoBean.trugTracCodgIsGatherCount) {
                                            indexTemp = index
                                            lastIndex = selectIndex.value ?: -1
                                            selectIndex.postValue(index)
                                            return@layer
                                        }
                                    }
                                }
                            }
                            //选中的时候就算没有查到也要去往里面加
                            if (selectIndex.value != -1) {
                                var temp =
                                    prescriptioninfo.value?.get(0)?.drugInfoList?.get(selectIndex.value!!)
                                if (!temp!!.trugTracCodgIsGatherCount) {
                                    selectIndex.postValue(selectIndex.value)
                                }
                                baseUiModel.postValue(BaseUiModel(showLoading = false))
                            } else {
                                if (indexTemp==-1){
                                    baseUiModel.postValue(BaseUiModel(showLoading = false,showError = "未找到与溯源码匹配的药品,请手动选中到待扫描的药品"))
                                }else{
                                    baseUiModel.postValue(BaseUiModel(showLoading = false))
                                }
                            }

                        }
                    }else{
                        baseUiModel.postValue(BaseUiModel(showLoading = false,showError = result.data.data.gatherMsg))
                    }

                }else if (result is Result.Error){
                    baseUiModel.postValue(BaseUiModel(showLoading = false,showError = result.errorData?:result.exception.message))
                }
            }
        }
    }

    /**
     * 保存数据
     */
    fun finishScanDrugCode(finishRequest: FinishRequest){
        viewModelScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                baseUiModel.postValue(BaseUiModel(showLoading = true))
                val result = repository.finishScanDrugCode(GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(finishRequest))
                if (result is Result.Success){
                    baseUiModel.postValue(BaseUiModel(showLoading = false,showSuccess = true))
                    barcode = ""
                    prescriptioninfo.postValue(mutableListOf())
                    Prescriptionbarcode = ""
                    lastIndex = -1
                    canAdd = false
                    usedCount = "0"
                    trugTracCodgIsGatherData=null
                }else if (result is Result.Error){
                    baseUiModel.postValue(BaseUiModel(showLoading = false,showError = result.errorData?:result.exception.message))
                }
            }
        }
    }
}